#include "selfinfowidget.h"
#include "qpushbutton.h"
#include "selfinfowidget.h"

#include "Debug.h"
#include "model/datacenter.h"
#include "toast.h"

SelfInfoWidget::SelfInfoWidget(const UserInfo* userInfo, QWidget* parent): QDialog(parent) {
    setFixedSize(288, 150);
    setWindowIcon(QIcon(":/resource/image/logo.png"));
    setWindowTitle("个人信息");
    // 设置关闭后⾃动销毁
    setAttribute(Qt::WA_DeleteOnClose);
    // 设置窗口出现的位置
    move(QCursor::pos());
    setStyleSheet("QWidget { background-color: #ffffff; font-size: 12px; } "
                  "QPushButton { border: none; background-color: white; } "
                  "QPushButton:hover { background-color: rgb(235, 235, 235); }"
                  "QPushButton:pressed { background-color:  #D2D2D2; }"
                  "QLineEdit { background-color: transparent; border: none; }");

    m_gridLayout = new QGridLayout();

    QHBoxLayout* layout = new QHBoxLayout();
    layout->setContentsMargins(15, 10, 15, 10);
    layout->setSpacing(10);
    this->setLayout(layout);

    // 添加用户头像
    m_avatar = new QPushButton();
    m_avatar->setFixedSize(60, 60);
    m_avatar->setIconSize(QSize(60, 60));
    m_avatar->setStyleSheet("QPushButton { border: none; background-color: white; }");
    m_avatar->setCursor(Qt::PointingHandCursor);
    layout->addWidget(m_avatar, 0, Qt::AlignTop);

    m_gridLayout = new QGridLayout();
    m_gridLayout->setContentsMargins(0, 0, 0, 0);
    m_gridLayout->setSpacing(5);
    m_gridLayout->setAlignment(Qt::AlignTop);
    layout->addLayout(m_gridLayout);

    QSize size(120, 15);
    // 4.1 ⽤户 id (不能编辑, ⽆需切换)
    QLabel* idTag = new QLabel(this);
    idTag->setStyleSheet("QLabel { font-weight: 800; }");
    idTag->setText("序号");
    QLabel* idLabel = new QLabel(this);

    QIcon modifyIcon(":/resource/image/modify.png");
    QIcon submitIcon(":/resource/image/submit.png");

    // 4.2 ⽤户昵称
    QLabel* nameTag = new QLabel(this);
    nameTag->setText("昵称");
    nameTag->setStyleSheet("QLabel { font-weight: 800; }");
    m_nameLabel = new QLabel(this);
    m_nameLabel->setFixedSize(size);
    m_nameEdit = new QLineEdit(this);
    m_nameEdit->setFixedSize(size);
    m_nameModifyBtn = new QPushButton(this);
    m_nameModifyBtn->setIcon(modifyIcon);
    m_nameSubmitBtn = new QPushButton(this);
    m_nameSubmitBtn->setIcon(submitIcon);

    m_nameEdit->hide();
    m_nameSubmitBtn->hide();

    // 4.3 ⽤户签名
    QLabel* descTag = new QLabel(this);
    descTag->setText("签名");
    descTag->setStyleSheet("QLabel { font-weight: 800; }");
    m_descLabel = new QLabel(this);
    m_descLabel->setFixedSize(size);
    m_descEdit = new QLineEdit(this);
    m_descEdit->setFixedSize(size);
    m_descModifyBtn = new QPushButton(this);
    m_descModifyBtn->setIcon(modifyIcon);
    m_descSubmitBtn = new QPushButton(this);
    m_descSubmitBtn->setIcon(submitIcon);
    m_descEdit->hide();
    m_descSubmitBtn->hide();

    // 4.4 ⽤户电话
    QLabel* phoneTag = new QLabel(this);
    phoneTag->setText("电话");
    phoneTag->setStyleSheet("QLabel { font-weight: 800; }");
    m_phoneLabel = new QLabel(this);
    m_phoneLabel->setFixedSize(size);
    m_phoneEdit = new QLineEdit(this);
    m_phoneEdit->setFixedSize(size);
    m_phoneModifyBtn = new QPushButton(this);
    m_phoneModifyBtn->setIcon(modifyIcon);
    m_phoneSubmitBtn = new QPushButton(this);
    m_phoneSubmitBtn->setIcon(submitIcon);
    m_phoneEdit->hide();
    m_phoneSubmitBtn->hide();

    m_verifyCodeEdit = new QLineEdit(this);
    m_verifyCodeEdit->setFixedSize(size);
    m_verifyCodeEdit->setPlaceholderText("验证码");
    m_verifyCodeEdit->hide();
    // 通过这个按钮来显⽰发送间隔时间的倒计时.
    m_sendVerifyCodeBtn = new QPushButton(this);
    m_sendVerifyCodeBtn->setText("获取");
    m_sendVerifyCodeBtn->hide();

    m_gridLayout->addWidget(idTag, 0, 0);
    m_gridLayout->addWidget(idLabel, 0, 1);

    m_gridLayout->addWidget(nameTag, 1, 0);
    m_gridLayout->addWidget(m_nameLabel, 1, 1);
    m_gridLayout->addWidget(m_nameModifyBtn, 1, 2);

    m_gridLayout->addWidget(descTag, 2, 0);
    m_gridLayout->addWidget(m_descLabel, 2, 1);
    m_gridLayout->addWidget(m_descModifyBtn, 2, 2);

    m_gridLayout->addWidget(phoneTag, 3, 0);
    m_gridLayout->addWidget(m_phoneLabel, 3, 1);
    m_gridLayout->addWidget(m_phoneModifyBtn, 3, 2);

    m_gridLayout->addWidget(m_verifyCodeEdit, 4, 1);
    m_gridLayout->addWidget(m_sendVerifyCodeBtn, 4, 2);

#if TEST_UI
    m_avatar->setIcon(QIcon(":/resource/image/defaultAvatar2.jpg"));
    idLabel->setText("1234");
    m_nameLabel->setText("张三");
    m_descLabel->setText("从今天开始认真敲代码");
    m_phoneLabel->setText("18612345678");    
#endif
    if(userInfo){
        m_avatar->setIcon(userInfo->m_avatar);
        idLabel->setText(userInfo->m_userId);
        m_nameLabel->setText(userInfo->m_nickName);
        m_descLabel->setText(userInfo->m_description);
        m_phoneLabel->setText(userInfo->m_phone);
    }

    // 初始化信号槽
    initSignalsAndSlots();
}

void SelfInfoWidget::initSignalsAndSlots()
{
    // 编辑昵称信号
    connect(m_nameModifyBtn, &QPushButton::clicked, this, [=]{
        m_nameEdit->setText(m_nameLabel->text());
        m_nameLabel->hide();
        m_nameModifyBtn->hide();
        m_gridLayout->removeWidget(m_nameLabel);
        m_gridLayout->removeWidget(m_nameModifyBtn);

        m_gridLayout->addWidget(m_nameEdit, 1, 1);
        m_gridLayout->addWidget(m_nameSubmitBtn, 1, 2);
        m_nameEdit->show();
        m_nameSubmitBtn->show();
    });
    // 提交修改昵称信号
    connect(m_nameSubmitBtn, &QPushButton::clicked, this, [=]{
        if(m_nameEdit->text().isEmpty() || m_nameEdit->text() == m_nameLabel->text()){
            clickNameSubmitBtnDone();
            LOG() << "昵称为空/昵称未做修改";
            return ;
        }
        auto dataCenter = model::DataCenter::getInstance();
        connect(dataCenter, &model::DataCenter::changeNickNameDone,
                this, &SelfInfoWidget::clickNameSubmitBtnDone, Qt::UniqueConnection);
        dataCenter->changeNickNameAsync(m_nameEdit->text());
    });

    // 编辑签名信号
    connect(m_descModifyBtn, &QPushButton::clicked, this, [=]{
        m_descEdit->setText(m_descLabel->text());
        m_descLabel->hide();
        m_descModifyBtn->hide();
        m_gridLayout->removeWidget(m_descLabel);
        m_gridLayout->removeWidget(m_descModifyBtn);

        m_gridLayout->addWidget(m_descEdit, 2, 1);
        m_gridLayout->addWidget(m_descSubmitBtn, 2, 2);
        m_descEdit->show();
        m_descSubmitBtn->show();
    });
    // 提交修改签名信号
    connect(m_descSubmitBtn, &QPushButton::clicked, this, [=]{
        if(m_descEdit->text().isEmpty() || m_descEdit->text() == m_descLabel->text()){
            clickSignatureSubmitBtnDone();
            LOG() << "签名为空/签名未做修改";
            return ;
        }
        auto dataCenter = model::DataCenter::getInstance();
        connect(dataCenter, &model::DataCenter::changeDescriptionDone,
                this, &SelfInfoWidget::clickSignatureSubmitBtnDone, Qt::UniqueConnection);
        dataCenter->changeDescriptionAsync(m_descEdit->text());
    });

    // 编辑电话信号
    connect(m_phoneModifyBtn, &QPushButton::clicked, this, [=]{
        m_phoneEdit->setText(m_phoneLabel->text());
        m_phoneLabel->hide();
        m_phoneModifyBtn->hide();
        m_gridLayout->removeWidget(m_phoneLabel);
        m_gridLayout->removeWidget(m_phoneModifyBtn);

        m_gridLayout->addWidget(m_phoneEdit, 3, 1);
        m_gridLayout->addWidget(m_phoneSubmitBtn, 3, 2);
        m_phoneEdit->show();
        m_phoneSubmitBtn->show();
        m_verifyCodeEdit->show();
        m_sendVerifyCodeBtn->show();
        m_verifyCodeEdit->setDisabled(false);
    });

    // 提交 核对修改电话的 验证码的信号
    connect(m_phoneSubmitBtn, &QPushButton::clicked, this, [=]{
        auto dataCenter = model::DataCenter::getInstance();
        QString verifyCodeId = dataCenter->getVerifyCodeId();
        if(verifyCodeId.isEmpty()){
            Toast::showMessage("验证码未收到，请稍等");
            return ;
        }
        QString verifyCode = m_verifyCodeEdit->text();
        if(verifyCode.isEmpty() ){
            Toast::showMessage("请输入验证码");
            return;
        }

        connect(dataCenter, &model::DataCenter::changePhoneDone,
                this, &SelfInfoWidget::clickPhoneSubmitBtnDone, Qt::UniqueConnection);
        dataCenter->changePhoneAsync(m_phoneEdit->text(), verifyCodeId, verifyCode);

        m_verifyCodeInterval = 1;
    });
    // 提交获取验证码信号
    connect(m_sendVerifyCodeBtn, &QPushButton::clicked, this, [=]{
        QString phone = m_phoneEdit->text().trimmed();
        // 验证手机号的格式
        QString err = model::verifyPhone(phone);
        LOG() << "返回的结果" << err;
        if(!err.isEmpty()){
            Toast::showMessage(err);
            return ;
        }else if(phone == m_phoneLabel->text()){
            Toast::showMessage("手机号相同，无需修改");
            return ;
        }

        // 发送验证码网络请求
        model::DataCenter* dataCenter = model::DataCenter::getInstance();
        connect(dataCenter, &model::DataCenter::getVerifyCodeDone,
                this, &SelfInfoWidget::clickVerifyCodeDone ,Qt::UniqueConnection);
        dataCenter->getVerifyCodeAsync(phone);
        // 禁用按钮
        m_sendVerifyCodeBtn->setEnabled(false);
        m_phoneEdit->setEnabled(false);
    });

    // 提交更换头像信号
    connect(m_avatar, &QPushButton::clicked, this, [=]{
        QString filter = "Image Files (*.png *.jpg *.bmp *.tiff)";
        QString filePath = QFileDialog::getOpenFileName(this, tr("选择头像"),  QDir::homePath(),filter);

        if(filePath.isEmpty()){
            LOG() << "取消打开文件";
            return ;
        }

        // 拿到图片内容
        QByteArray imageBytes = model::loadImageToByteArray(filePath);

        // 发送网络请求
        model::DataCenter* dataCenter = model::DataCenter::getInstance();
        connect(dataCenter, &model::DataCenter::changeAvatarDone,
                this, &SelfInfoWidget::clickAvatarDone, Qt::UniqueConnection);
        dataCenter->changeAvatarAsync(imageBytes);
    });
}

void SelfInfoWidget::clickNameSubmitBtnDone()
{
    // 隐藏和移除原有按钮
    m_nameEdit->hide();
    m_nameSubmitBtn->hide();
    m_gridLayout->removeWidget(m_nameEdit);
    m_gridLayout->removeWidget(m_nameSubmitBtn);
    // 显示和添加更新后按钮
    m_nameLabel->setText(m_nameEdit->text());
    m_gridLayout->addWidget(m_nameLabel, 1, 1);
    m_gridLayout->addWidget(m_nameModifyBtn, 1, 2);
    m_nameLabel->show();
    m_nameModifyBtn->show();
}

void SelfInfoWidget::clickSignatureSubmitBtnDone()
{
    // 隐藏和移除原有按钮
    m_descEdit->hide();
    m_descSubmitBtn->hide();
    m_gridLayout->removeWidget(m_descEdit);
    m_gridLayout->removeWidget(m_descSubmitBtn);
    // 显示和添加更新后按钮
    m_descLabel->setText(m_descEdit->text());
    m_gridLayout->addWidget(m_descLabel, 2, 1);
    m_gridLayout->addWidget(m_descModifyBtn, 2, 2);
    m_descLabel->show();
    m_descModifyBtn->show();
}

void SelfInfoWidget::clickAvatarDone()
{
    model::DataCenter* dataCenter = model::DataCenter::getInstance();
    m_avatar->setIcon(dataCenter->getMyself()->m_avatar);
}

void SelfInfoWidget::clickPhoneSubmitBtnDone()
{
    m_phoneEdit->hide();
    m_phoneSubmitBtn->hide();
    m_verifyCodeEdit->hide();
    m_verifyCodeEdit->setText("");   // 清空上次留下的验证码
    m_phoneEdit->setEnabled(true); // 重新激活可用
    m_sendVerifyCodeBtn->hide();
    m_gridLayout->removeWidget(m_phoneEdit);
    m_gridLayout->removeWidget(m_phoneSubmitBtn);

    m_gridLayout->addWidget(m_phoneLabel, 3, 1);
    m_gridLayout->addWidget(m_phoneModifyBtn, 3, 2);
    m_phoneLabel->setText(m_phoneEdit->text());
    m_phoneLabel->show();
    m_phoneLabel->setFocus();
    m_phoneModifyBtn->show();
}

void SelfInfoWidget::clickVerifyCodeDone()
{
    QTimer* timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, [=]{
        if(m_verifyCodeInterval > 0){
            m_sendVerifyCodeBtn->setText(QString::number(--m_verifyCodeInterval)+'s');
        }else{
            m_sendVerifyCodeBtn->setEnabled(true);
            m_sendVerifyCodeBtn->setText("获取");
            m_verifyCodeInterval = MAX_INTERVAL;
            timer->stop();
            timer->deleteLater();
        }
    });
    timer->start(1000);
}
